package me.jtx.poplar.core.data;

import java.io.Serializable;
import java.util.Collection;

import org.hibernate.criterion.Order;

import me.jtx.poplar.core.exception.database.NotFoundException;
import me.jtx.poplar.core.validation.EntityValidator;
import me.jtx.poplar.core.validation.Validity;

/**
 * BaseService implementation for basic access to service methods of crud
 * operation on entity
 * 
 * @param <T>
 * @param <ID>
 *
 * @author: Tong Huazhong(jsyzthz@gmail.com)
 * @copyright: &copy; 2016, Tong Huazhong
 */
public abstract class BaseJpaServiceImpl<T extends Entity, ID extends Serializable> implements BaseService<T, ID> {
	protected BaseJpaRepository<T, ID> baseJpaRepository;
	protected Class<T> entityClass;
	protected String nfEntityMsg;
	protected int nfEntityCode;

	@Override
	public T insert(T object) throws Exception {
		return baseJpaRepository.insert(object);
	}

	@Override
	public T update(T object) throws Exception {
		return baseJpaRepository.update(object);
	}

	@Override
	public void delete(T object) throws Exception {
		baseJpaRepository.delete(object);
	}

	@Override
	public T findById(ID id) throws Exception {
		T result = baseJpaRepository.findById(id);

		if (result != null)
			return result;
		else
			throw new NotFoundException(nfEntityMsg, nfEntityCode);
	}

	@Override
	public Collection<T> findAllByPage(int pageNum, int countPerPage, Order order) throws Exception {
		return null; // To change body of implemented methods use File |
						// Settings | File Templates.
	}

	@Override
	public Validity validate(T object) {
		EntityValidator<T> entityValidator = new EntityValidator<T>();
		return entityValidator.validate(object, entityClass);
	}
}
